<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>我的店铺</el-breadcrumb-item>
      <el-breadcrumb-item>店铺基础信息</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-form
        ref="shopInfoForm"
        :model="shopList"
        label-width="120px"
        label-position="left"
        :rules="shopListRules"
      >
        <div class="flexbox">
          <div class="left">
            <el-form-item label="店铺ID">
              <el-input v-model="shopList.shop_id" disabled></el-input>
            </el-form-item>
            <el-form-item label="店铺名称" prop="shop_name">
              <el-input v-model="shopList.shop_name"></el-input>
            </el-form-item>
            <el-form-item label="分店名称" prop="subbranch_name">
              <el-input v-model="shopList.subbranch_name" placeholder="请输入分店名称"></el-input>
            </el-form-item>
            <el-form-item label="所属行业" prop="value">
              <el-select v-model="shopList.value" placeholder="请选择" @change="changeBusiness">
                <el-option v-for="(item,index) in shopList.business" :key="index" :value="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="身份证号" prop="identity_card">
              <el-input v-model="shopList.identity_card"></el-input>
            </el-form-item>
            <el-form-item label="身份证正面照" prop="front">
              <input
                type="file"
                @change="uploadFront"
                ref="frontRef"
                hidden
                accept="image/gif, image/jpeg"
              />
              <el-image :src="shopList.front" fit="cover"></el-image>
              <a href="javascript:;" @click="uploadFrontBtn">重新上传</a>
            </el-form-item>
            <el-form-item label="身份证反面照" prop="reverse_side">
              <input
                type="file"
                @change="uploadReverseSide"
                ref="reverseSideRef"
                accept="image/gif, image/jpeg"
                hidden
              />
              <el-image :src="shopList.reverse_side" fit="cover"></el-image>
              <a href="javascript:;" @click="uploadReverseSideBtn">重新上传</a>
            </el-form-item>
          </div>
          <div>
            <el-form-item label="店铺头像" prop="shop_avatar">
              <input
                type="file"
                @change="uploadShopAvatar"
                ref="shopAvatarRef"
                accept="image/gif, image/jpeg"
                hidden
              />
              <el-image :src="shopList.shop_avatar" fit="cover"></el-image>
              <a href="javascript:;" @click="uploadShopAvatarBtn">重新上传</a>
            </el-form-item>
            <el-form-item label="主要产品图" prop="product_photo">
              <input
                type="file"
                @change="uploadProductPhoto"
                ref="productPhotoRef"
                accept="image/gif, image/jpeg"
                hidden
              />
              <el-image :src="shopList.product_photo" fit="cover"></el-image>
              <a href="javascript:;" @click="uploadProductPhotoBtn">重新上传</a>
            </el-form-item>
            <el-form-item label="店铺实拍图" prop="shop_photo">
              <div v-for="(item, index) in shopList.shop_photo" :key="index" class="shop-photo">
                <el-image :src="item" fit="cover"></el-image>
                <i :class="index === 0 ?'' : 'el-icon-delete'" @click="deleteShopPhoto(index)"></i>
              </div>
              <input
                type="file"
                @change="uploadShopPhoto"
                ref="shopPhotoRef"
                accept="image/gif, image/jpeg"
                hidden
                multiple
              />
              <a href="javascript:;" @click="uploadShopPhotoBtn">重新上传</a>
            </el-form-item>
            <el-form-item label="营业证件照" prop="business_license">
              <div
                v-for="(item, index) in shopList.business_license"
                :key="index"
                class="shop-photo"
              >
                <el-image :src="item" fit="cover"></el-image>
                <i
                  :class="index === 0 ?'' : 'el-icon-delete'"
                  @click="deleteBusinessLicense(index)"
                ></i>
              </div>
              <input
                type="file"
                @change="uploadBusinessLicense"
                ref="businessLicenseRef"
                hidden
                accept="image/gif, image/jpeg"
                multiple
              />
              <a href="javascript:;" @click="uploadBusinessLicenseBtn">重新上传</a>
            </el-form-item>
          </div>
        </div>
        <div class="pl120">
          <el-form-item label="店铺地址" prop="address">
            <div class="amap-page-container">
              <div id="allmap" ref="allmap"></div>
            </div>
            <div class="address">
              <el-input v-model="shopList.address.address_prefix" placeholder="通过地图选择地址"></el-input>
              <el-input v-model="shopList.address.address_suffix" placeholder="输入详细地址(例如:门牌号)"></el-input>
            </div>
          </el-form-item>
          <el-form-item label="联系方式" prop="contact_way">
            <el-input v-model="shopList.contact_way"></el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="codeSms">
            <el-input v-model="shopList.codeSms">
              <el-button slot="append" @click="sendSmsBtn" v-if="!show">发送验证码</el-button>
              <el-button slot="append" v-else>{{time}}秒后重新发送</el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="营业时间" class="open_time" prop="open_time">
            <el-time-picker
              is-range
              v-model="shopList.open_time"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围"
              @change="timeChange"
            ></el-time-picker>
          </el-form-item>
          <el-form-item label="发货方式" class="shipments_way" prop="shipments_way">
            <el-checkbox-group v-model="shopList.shipments_way" @change="checkChange">
              <el-checkbox label="到店自提"></el-checkbox>
              <el-checkbox label="同城配送">
                同城配送
                <div>
                  <span>起配价</span>
                  <input type="text" class="price" v-model="shopList.distributionTc.startPrice" />
                  <span class="unit">元</span>
                  <span class="text">配送费</span>
                  <input type="text" class="price" v-model="shopList.distributionTc.price" />
                  <span class="unit">元</span>
                  <div class="distribution-time">
                    <span>配送时间</span>
                    <el-time-picker
                      is-range
                      v-model="shopList.distributionTc.open_time"
                      range-separator="至"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      placeholder="选择时间范围"
                      @change="timeTcChange"
                    ></el-time-picker>
                  </div>
                </div>
              </el-checkbox>
              <el-checkbox label="区域配送">
                区域配送
                <div>
                  <span>配送时间</span>
                  <el-time-picker
                    is-range
                    v-model="shopList.distributionQy.open_time"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    placeholder="选择时间范围"
                    @change="timeQyChange"
                  ></el-time-picker>
                  <div class="distribution-time">
                    <span>起配价</span>
                    <input type="text" class="price" v-model="shopList.distributionQy.startPrice" />
                    <span class="unit">元</span>
                    <span class="text">配送范围</span>
                    <input
                      type="text"
                      class="price"
                      v-model="shopList.distributionQy.distribution_scope"
                    />
                    <span class="unit">公里(以内)</span>
                    <span class="text">配送费</span>
                    <input type="text" class="price" v-model="shopList.distributionQy.price" />
                    <span class="unit">元</span>
                  </div>
                </div>
              </el-checkbox>
              <el-checkbox label="跨域配送">
                跨域配送
                <div>
                  <span class="text">配送费</span>
                  <input
                    type="text"
                    class="price"
                    v-model="shopList.distributionKy.distribution_price"
                  />
                  <span class="unit">元</span>
                </div>
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="共享模式" class="sharing_model">
            <i class="el-icon-warning"></i>
            <div>
              <el-checkbox
                v-model="shopList.sharing_model"
                label="开启共享模式"
                size="medium"
                @change="changeSm"
              ></el-checkbox>
            </div>
          </el-form-item>
        </div>
        <el-button
          type="primary"
          v-loading="loading"
          element-loading-text="保存中"
          element-loading-spinner="el-icon-loading"
          class="saveBtn"
          @click="submitForm"
        >保存</el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import '@/mock/lwbmock.js'
import moment from 'moment'
export default {
  name: 'shopInfo',
  components: {},
  props: {},
  data () {
    var checkCard = (rule, value, cb) => {
      const regCard = /(^\d{18}$)|(^\d{17}(\d|X|x)$)/
      if (regCard.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的身份证'))
    }
    var checkPhoto = (rule, value, cb) => {
      const regPhoto = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|17[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
      if (regPhoto.test(value)) {
        return cb()
      }
      cb(new Error('请输入正确的联系方式'))
    }
    return {
      shopList: {
        //   shop_id: '',
        //   shop_name: '',
        //   subbranch_name: '',
        //   // 所属行业
        //   value: '',
        //   identity_card: '',
        //   front: '',
        //   reverse_side: '',
        //   shop_avatar: '',
        //   product_photo: '',
        //   shop_photo: [],
        //   business_license: [],
        //   // 店铺地址
        //   address: {
        //     address_prefix: '',
        //     address_suffix: ''
        // },
        // contact_way: '',
        // open_time: [new Date(2016, 9, 10, 8, 40), new Date(2016, 9, 10, 9, 40)],
        // shipments_way: [],
        // distributionTc: {
        //   open_time: [],
        //   startPrice: '',
        //   price: ''
        // },
        // distributionQy: {
        //   open_time: [new Date(2016, 9, 10, 8, 40), new Date(2016, 9, 10, 9, 40)],
        //   startPrice: '',
        //   distribution_scope: '',
        //   price: ''
        // },
        // distributionKy: {
        //   distribution_price: ''
        // },
        // sharing_model: false
      },
      //地图对象
      mymap: JSON.parse(window.localStorage.getItem('mapObj')) || {
        lng: '112.93',
        lat: '28.23',
        pt: ''
      },
      time: 60,
      show: false,
      checkList: false,
      loading: false,
      shopListRules: {
        shop_name: [
          { required: true, message: '请输入店铺名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        value: [
          { required: true, message: '请选择所属行业', trigger: 'change' }
        ],
        identity_card: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { validator: checkCard, trigger: 'blur' }
        ],
        front: [
          { required: true, message: '请上传身份证正面照', trigger: 'change' }
        ],
        reverse_side: [
          { required: true, message: '请上传身份证反面照', trigger: 'change' }
        ],
        shop_avatar: [
          { required: true, message: '请上传店铺头像', trigger: 'change' }
        ],
        product_photo: [
          { required: true, message: '请上传主要产品图', trigger: 'change' }
        ],
        shop_photo: [
          { required: true, message: '请上传店铺实拍图', trigger: 'change' }
        ],
        business_license: [
          { required: true, message: '请上传营业证件照', trigger: 'change' }
        ],
        address: [
          { required: true, message: '请选择地址', trigger: 'blur' }
        ],
        contact_way: [
          { required: true, message: '请输入联系方式', trigger: 'blur' },
          { validator: checkPhoto, trigger: 'blur' }
        ],
        codeSms: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ],
        open_time: [
          { required: true, message: '请选择营业时间', trigger: 'change' }
        ],
        shipments_way: [
          { required: true, message: '请选择发货方式', trigger: 'change' }
        ]
      },
      index: null
    }
  },
  computed: {},
  watch: {},
  created () {
    if (window.localStorage.getItem('SHOPLIST')) {
      this.shopList = JSON.parse(window.localStorage.getItem('SHOPLIST'))
    } else {
      this.getShopInfo()
      window.localStorage.setItem('mapObj', JSON.stringify(this.mymap))
    }
  },
  methods: {
    async getShopInfo () {
      const { data } = await this.axios.get('/shop')
      this.shopList = data.data
      window.localStorage.setItem('SHOPLIST', JSON.stringify(data.data))
    },
    ready: function () {
      const that = this
      var map = new BMap.Map('allmap', { minZoom: 14, maxZoom: 16 })
      var point = new BMap.Point(this.mymap.lng, this.mymap.lat)
      map.centerAndZoom(point, 16)
      map.enableScrollWheelZoom()
      var geoc = new BMap.Geocoder()
      map.addOverlay(new BMap.Marker(this.mymap.pt))
      map.addEventListener('click', function (e) {
        that.shopList.address.address_suffix = ''
        map.clearOverlays()
        var pt = e.point
        that.mymap.pt = pt
        that.mymap.lng = pt.lng
        that.mymap.lat = pt.lat
        geoc.getLocation(pt, (rs) => {
          map.addOverlay(new BMap.Marker(pt))
          var addComp = rs.addressComponents
          that.shopList.address.address_prefix = `${addComp.province}${addComp.city}${addComp.district}${addComp.street}`
        })
      })
    },
    changeBusiness (val) {
      this.shopList.value = val
    },
    uploadFrontBtn () {
      this.$refs.frontRef.click()
    },
    uploadReverseSideBtn () {
      this.$refs.reverseSideRef.click()
    },
    uploadShopAvatarBtn () {
      this.$refs.shopAvatarRef.click()
    },
    uploadProductPhotoBtn () {
      this.$refs.productPhotoRef.click()
    },
    uploadShopPhotoBtn () {
      this.$refs.shopPhotoRef.click()
    },
    uploadBusinessLicenseBtn () {
      this.$refs.businessLicenseRef.click()
    },
    uploadFront () {
      if (!this.$refs.frontRef.files[0]) return
      const img = this.$refs.frontRef.files[0]
      const f = new FileReader()
      f.readAsDataURL(img)
      f.onload = () => {
        this.shopList.front = f.result
      }
    },
    uploadReverseSide () {
      if (!this.$refs.reverseSideRef.files[0]) return
      const img = this.$refs.reverseSideRef.files[0]
      const f = new FileReader()
      f.readAsDataURL(img)
      f.onload = () => {
        this.shopList.reverse_side = f.result
      }
    },
    uploadShopAvatar () {
      if (!this.$refs.shopAvatarRef.files[0]) return
      const img = this.$refs.shopAvatarRef.files[0]
      const f = new FileReader()
      f.readAsDataURL(img)
      f.onload = () => {
        this.shopList.shop_avatar = f.result
      }
    },
    uploadProductPhoto () {
      if (!this.$refs.productPhotoRef.files[0]) return
      const img = this.$refs.productPhotoRef.files[0]
      const f = new FileReader()
      f.readAsDataURL(img)
      f.onload = () => {
        this.shopList.product_photo = f.result
      }
    },
    uploadShopPhoto () {
      if (!this.$refs.shopPhotoRef.files[0]) return
      const img = this.$refs.shopPhotoRef.files
      const images = Array.from(img)
      if (images.length > 2) return
      this.shopList.shop_photo = []
      images.forEach(item => {
        const f = new FileReader()
        f.readAsDataURL(item)
        f.onload = () => {
          this.shopList.shop_photo.unshift(f.result)
        }
      })
    },
    uploadBusinessLicense () {
      if (!this.$refs.businessLicenseRef.files[0]) return
      const img = this.$refs.businessLicenseRef.files
      const images = Array.from(img)
      if (images.length > 3) return
      this.shopList.business_license = []
      images.forEach(item => {
        const f = new FileReader()
        f.readAsDataURL(item)
        f.onload = () => {
          this.shopList.business_license.unshift(f.result)
        }
      })
    },
    deleteShopPhoto (index) {
      this.shopList.shop_photo.splice(index, 1)
    },
    deleteBusinessLicense (index) {
      this.shopList.business_license.splice(index, 1)
    },
    async sendSmsBtn () {
      try {
        await this.$refs.shopInfoForm.validateField('contact_way')
      } catch (err) {
        return false
      }
      this.show = true
      this.countDown()
      await this.axios.get('http://ttapi.research.itcast.cn/app/v1_0/sms/codes/' + this.shopList.contact_way)
      this.$message.success('发送成功')
    },
    countDown () {
      this.index = setInterval(function () {
        this.time--
        if (this.time < 1) {
          clearInterval(this.index)
          this.time = 60
          this.show = false
        }
      }.bind(this), 1000)
    },
    timeChange (val) {
      this.shopList.open_time = []
      // this.shopList.open_time = [new Date(moment(val[0]).format('YYYY,MM,DD,h,mm')), new Date(moment(val[1]).format('YYYY,MM,DD,h,mm'))]
      val.forEach(item => {
        const val1 = moment(item).format('YYYY-MM-DD h:mm')
        // console.log(val1)
        this.shopList.open_time.push(val1)
      })
    },
    checkChange (val) {
      this.shopList.shipments_way = val
    },
    changeSm (val) {
      this.shopList.sharing_model = val
    },
    timeTcChange (val) {
      this.shopList.distributionTc.open_time = []
      val.forEach(item => {
        const val1 = moment(item).format('YYYY-MM-DD h:mm')
        this.shopList.distributionTc.open_time.push(val1)
      })
    },
    timeQyChange (val) {
      this.shopList.distributionQy.open_time = []
      val.forEach(item => {
        const val1 = moment(item).format('YYYY-MM-DD h:mm')
        this.shopList.distributionQy.open_time.push(val1)
      })
    },
    submitForm () {
      this.loading = true
      this.$refs.shopInfoForm.validate(async valid => {
        if (!valid) {
          this.loading = false
          this.$message.error('必填项不能为空')
          return false
        }
        if (this.shopList.shipments_way.indexOf('同城配送') !== -1) {
          if (this.shopList.distributionTc.startPrice === '' || this.shopList.distributionTc.price === '') {
            this.loading = false
            return this.$message.error('请配置同城配送相关信息')
          }
        }
        if (this.shopList.shipments_way.indexOf('区域配送') !== -1) {
          if (this.shopList.distributionQy.startPrice === '' || this.shopList.distributionQy.distribution_scope === '' || this.shopList.distributionQy.price === '') {
            this.loading = false
            return this.$message.error('请配置区域配送相关信息')
          }
        }
        if (this.shopList.shipments_way.indexOf('跨域配送') !== -1) {
          if (this.shopList.distributionKy.distribution_price === '') {
            this.loading = false
            return this.$message.error('请配置跨域配送相关信息')
          }
        }
        window.localStorage.setItem('SHOPLIST', JSON.stringify(this.shopList))
        window.localStorage.setItem('mapObj', JSON.stringify(this.mymap))
        try {
          await this.axios.post('http://ttapi.research.itcast.cn/app/v1_0/authorizations',
            {
              mobile: this.shopList.contact_way,
              code: this.shopList.codeSms
            }
          )
          this.loading = false
          this.$message.success('保存成功')
          this.shopList.codeSms = ''
          clearInterval(this.index)
          this.show = false
           window.localStorage.setItem('SHOPLIST', JSON.stringify(this.shopList))
        } catch (err) {
          this.$message.error('验证码错误,保存失败')
          this.loading = false
        }
      })
    }
  },
  mounted () {
    this.ready()
  }
}
</script>

<style scoped lang="less">
.address {
  margin-top: 20px;
}
#allmap {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}
.el-card {
  padding: 20px 0;
}
.backBtn {
  margin-left: 10px;
  font-size: 16px;
}
/deep/.el-form-item__error {
  margin-left: 50px;
}
.el-form {
  .flexbox {
    .left {
      .el-image {
        margin-left: 50px;
      }
    }
    display: flex;
    div {
      flex: 1;
      .el-image {
        position: relative;
        width: 90px;
        height: 70px;
        vertical-align: middle;
        margin-right: 10px;
        border: 4px solid #ccc;
        .photo-delete {
          width: 200px;
          height: 200px;
          position: absolute;
          top: 0px;
          right: 0px;
          font-size: 50px;
          z-index: 10;
          background-color: pink;
        }
      }
    }
    /deep/.el-form-item__label:before {
      margin-left: -10px;
    }
    font-size: 20px;
    padding-left: 120px;
    /deep/.el-form-item__label {
      font-size: 16px;
    }
    .el-input,
    .el-select {
      width: 300px;
      margin-left: 50px;
      font-size: 16px;
    }
  }
  .saveBtn {
    width: 120px;
    margin-left: 120px;
    margin-top: 10px;
  }
  .pl120 {
    padding-left: 120px;
    /deep/.el-form-item__label {
      font-size: 16px;
    }
    /deep/.el-checkbox__inner {
      border-radius: 50%;
    }

    .el-checkbox__label {
      color: #000;
    }
    .shipments_way,
    .sharing_model {
      div {
        margin-left: 50px;
        .el-checkbox__label {
          font-size: 16px;
        }
      }
    }
    .sharing_model {
      position: relative;
      padding-left: 20px;
      div {
        margin-left: 30px;
      }
      .el-icon-warning {
        position: absolute;
        left: -140px;
        top: 10px;
        font-size: 16px;
        color: red;
      }
    }
    .el-checkbox-group {
      display: flex;
      flex-direction: column;
    }
    /deep/.el-checkbox__label {
      display: unset;
      color: #000;
    }
    .sharing_model {
      /deep/.el-checkbox__inner {
        border-radius: 0;
      }
    }
    .price {
      width: 50px;
      height: 30px;
      margin: 0 10px;
      outline: none;
      text-align: center;
    }
    .text {
      margin-left: 15px;
    }
    .unit {
      font-size: 12px;
    }
    .distribution-time {
      margin: 15px 0px 0 !important;
    }
    .el-input {
      margin-left: 50px;
      width: 300px;
      font-size: 16px;
    }
    .open_time {
      input {
        width: 120px;
        height: 30px;
        margin-left: 50px;
      }
    }
    .el-input__inner {
      margin-left: 50px;
    }
  }
  .amap-page-container {
    margin-top: 10px;
    width: 600px;
    height: 400px;
    border: 1px solid #000;
    margin-left: 50px;
  }
  .toolbar {
    z-index: 120;
  }
  .shop-photo {
    position: relative;
    display: inline-block;
    .el-icon-delete {
      position: absolute;
      top: 0px;
      right: 10px;
      font-size: 16px;
      color: #000;
    }
  }
  /deep/.el-loading-mask {
    line-height: 38px;
    .el-loading-spinner {
      i {
        font-size: 16px;
      }
      .el-loading-text {
        display: inline-block;
      }
    }
  }
}
</style>
